package cn.com.elite;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cntaiping.intserv.client.ISHttpClient;

public class ISPayServlet extends HttpServlet{
	private static final Log log=LogFactory.getLog(ISPayServlet.class);
	public static String Payment_url="";
	public static String PaymentQuery_url="";
	public static String PaymentCancel_url="";
	public static String AcceptProposalApp_url="";
	public static String indentity="";
	public static String authPasswd="";
	public static String MERCHANT_ID="";
	public static String MERCHANT_ID1="";
	public static cn.com.elite.ISBean ebean;
	public static WebApplicationContext wac;
	private String[] code={"GB","BX","C0","CX","DV","GR","HN","98","68","09"};
	public static Thread t;
	public static Thread t2;
	public static Thread t3;
	public static ISPayThread td;
	public static Tongbu5314Thread tongbu5314Thread;
	public static Chaxun5314Thread chaxun5314Thread;
	public static Thread t1;
	public static LoriThread td1;
	
	public ISBean getbean(){
		ServletContext application;    
        application = getServletContext();   
        wac=WebApplicationContextUtils.getWebApplicationContext(application);//获取spring的context  
        cn.com.elite.ISBean ebean=(cn.com.elite.ISBean)wac.getBean("ebean");  
        return ebean;
	} 
	public static Element ElementRoot(String xml) throws JDOMException, IOException {
		SAXBuilder saxBuilder=new SAXBuilder();
		StringReader stringIn=new StringReader(xml);
		Document document=saxBuilder.build(stringIn);
		return document.getRootElement();
	}
	public static String getElementValue(Element elmt) {
		return elmt==null?"":elmt.getValue();
	}
	public static String ISPayConnection(String url,String indentity,String authPasswd,String xml,String indentity_param,String indentity_value,String xmlfile) throws Exception{
		log.info("xml:"+xml);
		ISHttpClient client=new ISHttpClient();
		client.connect(url,null,indentity,authPasswd);
		client.addParameter(indentity_param,indentity_value);
		client.addParameter(xmlfile,xml);
		Date startDate = new Date();
		log.debug("调用client.doPost开始时间："+startDate.toString());
		String response=client.doPost(true);
		Date endDate=new Date();
		log.debug("调用client.doPost结束时间："+endDate.toString());
		long between=endDate.getTime()-startDate.getTime();
		log.debug("共用毫秒数："+between);
		return response;
	}
	public static String ISPayConnection1(String url,String indentity,String authPasswd,String xml,String indentity_param,String indentity_value,String xmlfile) throws Exception{
		log.info("xml:"+xml);
		String response="";
		HttpParams httpParameters = new BasicHttpParams();
		httpParameters.setBooleanParameter("http.protocol.expect-continue", false);
		HttpClient hc=new DefaultHttpClient(httpParameters);
		hc.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,60000);
		HttpPost httpPost=new HttpPost(url); 
		httpPost.addHeader("Connection", "close");
		List params=new ArrayList(); 
		NameValuePair pair1=new BasicNameValuePair(indentity,indentity_value);  
		log.debug("packet:"+xml);
	    NameValuePair pair2=new BasicNameValuePair(xmlfile,xml);  
	    params.add(pair1);  
	    params.add(pair2);
	    httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); 
	    HttpResponse ht=hc.execute(httpPost);
	    if(ht.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
	    	HttpEntity het=ht.getEntity();  
            InputStream is=het.getContent();  
            BufferedReader br=new BufferedReader(new InputStreamReader(is,"UTF-8"));  
            String readLine=null;  
            while((readLine =br.readLine())!=null){  
                response=response+readLine;  
            }  
            is.close();  
            br.close();
	    }else{
	    	log.error("ht.getStatusLine().getStatusCode():"+ht.getStatusLine().getStatusCode());
	    }
        log.debug("response:"+response);
		return response;
	}
	public void init(){
		Payment_url=this.getInitParameter("Payment_url");
		log.info("Payment_url:"+Payment_url);
		PaymentQuery_url=this.getInitParameter("PaymentQuery_url");
		log.info("PaymentQuery_url:"+PaymentQuery_url);
		PaymentCancel_url=this.getInitParameter("PaymentCancel_url");
		log.info("PaymentCancel_url:"+PaymentCancel_url);
		AcceptProposalApp_url=this.getInitParameter("AcceptProposalApp_url");
		log.info("AcceptProposalApp_url:"+AcceptProposalApp_url);
		indentity=this.getInitParameter("indentity");
		log.info("indentity:"+indentity);
		authPasswd=this.getInitParameter("authPasswd");
		log.info("authPasswd:"+authPasswd);
		MERCHANT_ID=this.getInitParameter("MERCHANT_ID");
		log.info("MERCHANT_ID:"+MERCHANT_ID);
		MERCHANT_ID1=this.getInitParameter("MERCHANT_ID1");
		log.info("MERCHANT_ID1:"+MERCHANT_ID1);
		String thread_flag=this.getInitParameter("thread_flag");
		log.info("thread_flag:"+thread_flag);
		String Tongbu5314_flag=this.getInitParameter("Tongbu5314_flag");
		log.info("Tongbu5314_flag:"+Tongbu5314_flag);
		String Chaxun5314_flag=this.getInitParameter("Chaxun5314_flag");
		log.info("Chaxun5314_flag:"+Chaxun5314_flag);
		ebean=getbean();
		if(Tongbu5314_flag.equals("1")){
			String Tongbu5314HZ=this.getInitParameter("Tongbu5314HZ");
			log.info("Tongbu5314HZ:"+Tongbu5314HZ);
			String TongbuNUM=this.getInitParameter("TongbuNUM");
			log.info("TongbuNUM:"+TongbuNUM);
			String Tongbu5314=this.getInitParameter("Tongbu5314");
			log.info("Tongbu5314:"+Tongbu5314);
			tongbu5314Thread=new Tongbu5314Thread();
			tongbu5314Thread.setHZ(Integer.parseInt(Tongbu5314HZ));
			tongbu5314Thread.setNum(Integer.parseInt(TongbuNUM));
			tongbu5314Thread.setUrl(Tongbu5314);
			t2=new Thread(tongbu5314Thread); 
	        t2.start(); //   启动任务	
		}
		if(Chaxun5314_flag.equals("1")){
			String Chaxun5314HZ=this.getInitParameter("Chaxun5314HZ");
			log.info("Chaxun5314HZ:"+Chaxun5314HZ);
			String Chaxun5314=this.getInitParameter("Chaxun5314");
			log.info("Chaxun5314:"+Chaxun5314);
			chaxun5314Thread=new Chaxun5314Thread();
			chaxun5314Thread.setHZ(Integer.parseInt(Chaxun5314HZ));
			chaxun5314Thread.setUrl(Chaxun5314);
			t3=new Thread(chaxun5314Thread); 
	        t3.start(); //   启动任务
		}
		if(thread_flag.equals("1")){
			com.elitecrm.service.coresync.CoreSyncService coreSyncService=(com.elitecrm.service.coresync.CoreSyncService)wac.getBean("syncCoreService");  
			String dotime1=this.getInitParameter("dotime");
			log.info("dotime1:"+dotime1);
			ISPayThread.dotime=dotime1;
			ISPayThread.coreSyncService=coreSyncService;
			td=new ISPayThread();
			t=new Thread(td); 
	        t.start(); //   启动任务
		}else{
			log.info("不启动夜间同步线程");
		}
		String thread_flag1=this.getInitParameter("thread_flag1");
		log.info("thread_flag1:"+thread_flag1);
		if(thread_flag1.equals("1")){
			com.elitecrm.service.coresync.CoreSyncService coreSyncService=(com.elitecrm.service.coresync.CoreSyncService)wac.getBean("syncCoreService");  
			String dotime1=this.getInitParameter("dotime1");
			log.info("dotime1:"+dotime1);
			LoriThread.dotime=dotime1;
			LoriThread.coreSyncService=coreSyncService;
			td1=new LoriThread();
			t1=new Thread(td1); 
	        t1.start(); //   启动任务
		}else{
			log.info("不启动夜间同步线程");
		}
	}

	public void doGet(HttpServletRequest request,HttpServletResponse response){
		this.doPost(request, response);
	}

	public static void PorcessLog(String xml,String OrderNo,String ProcessName,String ProcessID,int flag,String realtionid,DataSource dataSource){
		try{
			String param=xml;
			if(param.length()>1000){
				param=param.substring(0,1000);
			}
			ebean.ISIvrPay_log(OrderNo,ProcessName,param,ProcessID,flag,realtionid,dataSource);
		}catch(Exception e){
			try{
				ebean.ISIvrPay_log(OrderNo,ProcessName,"参数有非法字符",ProcessID,flag,realtionid,dataSource);
			}catch(Exception e1){
				log.error(Util.getERRO(e1));
			}
			log.error(Util.getERRO(e));
		}
	}
	private void InsertSql(String IVROrderNo,String RealOrderNo,int flag,DataSource dataSource1){
		String sql=" insert into IsPayOrderNo (IVROrderNo,RealOrderNo,flag,createdate)Values('"+IVROrderNo+"','"+RealOrderNo+"',"+flag+",sysdate)";
		int InsertSqlresult=ebean.update_sql(sql,dataSource1);
		log.info("InsertSqlresult:"+InsertSqlresult);
	}
	private String PayProcess(DataSource dataSource1,String IVROrderNo,String RealOrderNo,String BankAccount){
		String return_xml="<?xml version='1.0' encoding='UTF-8'?><Result><Code>CS02</Code><Msg>支付过程错误</Msg></Result>";
		String result="";
		String ORDER_NUMBER="";
		String RESPONSE_CODE="";
		String RESPONSE_DESC="";
		String BANK_CODE="";
		String ACCOUNT_TYPE="";
		String PAYMENT_ID=IVROrderNo;
		String PAYMENT_ID1="";
		String TRANS_DATE="";
		String TRANS_TIME="";
		String ERR_MSG="";
		String ERR_CODE="";
		String ISIvrPay_result="";
		int flag=0;	
		try{
			String sql="select HOLDER_NAME,HOLDER_CERTI_TYPE,HOLDER_CERTI_CODE,TRANS_AMT,CUR_TYPE," +
					"to_char(ValidateDate,'yyyymmdd') as ValidateDate from insurance_ivr where  order_no='"+IVROrderNo+"'";
			List list=ebean.chaxun_sql(sql,dataSource1);
			if(list!=null&&list.size()>0){
				Map map=(Map)list.get(0);
				String HOLDER_NAME=(String)map.get("HOLDER_NAME");
				String HOLDER_CERTI_TYPE=(String)map.get("HOLDER_CERTI_TYPE");
				String HOLDER_CERTI_CODE=(String)map.get("HOLDER_CERTI_CODE");
				String TRANS_AMT=map.get("TRANS_AMT")+"";
				String CUR_TYPE=(String)map.get("CUR_TYPE");
				String ValidateDate=(String)map.get("ValidateDate");
				String MERCHANTID="";
				String headjudge=IVROrderNo.substring(0,2);
				log.debug("headjudge"+headjudge);
				if(headjudge.equals("ec")){
					MERCHANTID=MERCHANT_ID1;
				}else{
					MERCHANTID=MERCHANT_ID;
				}
				String xml="<?xml version='1.0' encoding='UTF-8'?><BODY>" +
				"<MERCHANT_ID>"+MERCHANTID+"</MERCHANT_ID>" +
				"<PAYMENT_ID>"+RealOrderNo+"</PAYMENT_ID>" +
				"<FEE_TYPE></FEE_TYPE>" +
				"<PAY_WAY></PAY_WAY>" +
				"<BUSI_TYPE></BUSI_TYPE>" +
				"<BANK_ACCOUNT>"+BankAccount+"</BANK_ACCOUNT>" +
				"<BANK_CODE></BANK_CODE>" +
				"<HOLDER_NAME>"+HOLDER_NAME+"</HOLDER_NAME>" +
				"<HOLDER_CERTI_TYPE>"+HOLDER_CERTI_TYPE+"</HOLDER_CERTI_TYPE>" +
				"<HOLDER_CERTI_CODE>"+HOLDER_CERTI_CODE+"</HOLDER_CERTI_CODE>" +
				"<TRANS_AMT>"+TRANS_AMT+"</TRANS_AMT>" +
				"<CUR_TYPE>"+CUR_TYPE+"</CUR_TYPE>" +
				"<RESERVED1></RESERVED1>" +
				"<RESERVED2></RESERVED2>" +
				"</BODY>";
				PorcessLog(xml,IVROrderNo,"调用支付接口前","pay_02",100,"",dataSource1);
				try{
					result=ISPayConnection(Payment_url,indentity,authPasswd,xml,"indentity","300","xmlfile");
				}catch(Exception e1){
					return_xml="<?xml version='1.0' encoding='UTF-8'?><Result><Code>CS02</Code><Msg>银联交易超时或者网络不通</Msg></Result>";
					PorcessLog(result,IVROrderNo,"调用支付接口后","pay_03",2,"",dataSource1);
					log.error(Util.getERRO(e1));
					ISIvrPay_result=ebean.ISIvrPay(ORDER_NUMBER,RESPONSE_CODE, RESPONSE_DESC, BANK_CODE, ACCOUNT_TYPE, PAYMENT_ID1, TRANS_DATE, TRANS_TIME, ERR_MSG, ERR_CODE, BankAccount,flag,dataSource1,PAYMENT_ID,RealOrderNo);
					log.info("ISIvrPay_result:"+ISIvrPay_result);
					InsertSql(IVROrderNo,RealOrderNo,flag,dataSource1);
					return ISIvrPay_result;
				}
				try{
					Element root=ElementRoot(result);
					ORDER_NUMBER=getElementValue(root.getChild("ORDER_NUMBER"));
					RESPONSE_CODE=getElementValue(root.getChild("RESPONSE_CODE"));
					RESPONSE_DESC=getElementValue(root.getChild("RESPONSE_DESC"));
					BANK_CODE=getElementValue(root.getChild("BANK_CODE"));
					ACCOUNT_TYPE=getElementValue(root.getChild("ACCOUNT_TYPE"));
					PAYMENT_ID1=getElementValue(root.getChild("PAYMENT_ID"));
					TRANS_DATE=getElementValue(root.getChild("TRANS_DATE"));
					TRANS_TIME=getElementValue(root.getChild("TRANS_TIME"));
					ERR_MSG=getElementValue(root.getChild("ERR_MSG"));
					ERR_CODE=getElementValue(root.getChild("ERR_CODE"));
				}catch(Exception e2){
					return_xml="<?xml version='1.0' encoding='UTF-8'?><Result><Code>CS02</Code><Msg>银联支付返回报文为空或者格式错误</Msg></Result>";
					PorcessLog(result,IVROrderNo,"调用支付接口后","pay_03",3,"",dataSource1);
					ISIvrPay_result=ebean.ISIvrPay(ORDER_NUMBER,RESPONSE_CODE, RESPONSE_DESC, BANK_CODE, ACCOUNT_TYPE, PAYMENT_ID1, TRANS_DATE, TRANS_TIME, ERR_MSG, ERR_CODE, BankAccount,flag,dataSource1,PAYMENT_ID,RealOrderNo);
					log.info("ISIvrPay_result:"+ISIvrPay_result);
					InsertSql(IVROrderNo,RealOrderNo,flag,dataSource1);
					log.error(Util.getERRO(e2));
					return ISIvrPay_result;
				}
				if(RESPONSE_CODE.equals("00")){
					return_xml="<?xml version='1.0' encoding='UTF-8'?><Result><Code>00</Code><Msg>承兑或交易成功</Msg><OrderNo>"+IVROrderNo+"</OrderNo><ValidateDate>"+ValidateDate+"</ValidateDate></Result>";
					flag=1;
					PorcessLog(result,IVROrderNo,"调用支付接口后","pay_03",1,"",dataSource1);
				}else{
					return_xml="<?xml version='1.0' encoding='UTF-8'?><Result><Code>CS01</Code><Msg>"+RESPONSE_DESC+"</Msg></Result>";
					PorcessLog(result,IVROrderNo,"调用支付接口后","pay_03",0,"",dataSource1);
				}
				
			}
		}catch(Exception e){
			log.error(Util.getERRO(e));
		}
		ISIvrPay_result=ebean.ISIvrPay(ORDER_NUMBER,RESPONSE_CODE, RESPONSE_DESC, BANK_CODE, ACCOUNT_TYPE, PAYMENT_ID1, TRANS_DATE, TRANS_TIME, ERR_MSG, ERR_CODE, BankAccount,flag,dataSource1,PAYMENT_ID,RealOrderNo); 
		log.info("ISIvrPay_result:"+ISIvrPay_result);
		InsertSql(IVROrderNo,RealOrderNo,flag,dataSource1);
		return return_xml;
	}
    public static void main(String[] args){
		Date now=new Date(); 
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");//可以方便地修改日期格式
		String ValidateDate=dateFormat.format(now); 
		System.out.println(ValidateDate);
    }

	public void doPost(HttpServletRequest request,HttpServletResponse response){
		log.info("－－－－－－－－－－－－－－－－－－－ISPayServlet（265）－－－－－－－－－－－－－－－－－－");
		String ProjectID=request.getParameter("ProjectID"); 
		log.info("ProjectID:"+ProjectID);
		String OrderNo=request.getParameter("OrderNo");
		log.info("OrderNo:"+OrderNo);
		String BankAccount=request.getParameter("BankAccount");
		log.info("BankAccount:"+BankAccount);
		DataSource dataSource1=(DataSource)wac.getBean(ProjectID);
		PorcessLog("ProjectID:"+ProjectID+"-OrderNo:"+OrderNo+"-BankAccount:"+BankAccount,OrderNo,"接受到IVR传来参数","pay_01",100,"",dataSource1);
		String return_xml="<?xml version='1.0' encoding='UTF-8'?><Result><Code>CS01</Code><Msg>支付过程发生未知异常</Msg></Result>";	
		List OrderNo_list=ebean.chaxun_sql("select * from IsPayOrderNo where IVROrderNo='"+OrderNo+"'",dataSource1);
		if(OrderNo_list!=null&&OrderNo_list.size()>0){
			Map OrderNo_map=(Map)OrderNo_list.get(0);
			String OrderNo_flag=(String)OrderNo_map.get("flag");
			String IVROrderNo=(String)OrderNo_map.get("IVROrderNo");
			String RealOrderNo=(String)OrderNo_map.get("RealOrderNo");
			if(OrderNo_flag!=null){
				if(OrderNo_flag.equals("1")){  //支付成功返回
					Date now=new Date(); 
					SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");//可以方便地修改日期格式
					String ValidateDate=dateFormat.format(now); 
					return_xml="<?xml version='1.0' encoding='UTF-8'?><Result><Code>00</Code><Msg>承兑或交易成功</Msg><OrderNo>"+IVROrderNo+"</OrderNo><ValidateDate>"+ValidateDate+"</ValidateDate></Result>";
				}else if(OrderNo_flag.equals("0")){   //支付失败，继续支付
					return_xml=PayProcess(dataSource1,IVROrderNo,RealOrderNo,BankAccount);
				}else if(OrderNo_flag.equals("2")){   //超时或者网络不通
					String Query=IsPayInterface.getPaymentQuery(OrderNo,dataSource1);
					if(Query.equals("1")){
						Date now=new Date(); 
						SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");//可以方便地修改日期格式
						String ValidateDate=dateFormat.format(now); 
						return_xml="<?xml version='1.0' encoding='UTF-8'?><Result><Code>00</Code><Msg>承兑或交易成功</Msg><OrderNo>"+IVROrderNo+"</OrderNo><ValidateDate>"+ValidateDate+"</ValidateDate></Result>";
					}else if(Query.equals("2")){
						return_xml="<?xml version='1.0' encoding='UTF-8'?><Result><Code>CS02</Code><Msg>银联支付无返回或者返回异常</Msg></Result>";
					}else if(Query.equals("0")){
						return_xml=PayProcess(dataSource1,IVROrderNo,RealOrderNo,BankAccount);
					}
				}else if(OrderNo_flag.equals("3")){   //无返回
					return_xml="<?xml version='1.0' encoding='UTF-8'?><Result><Code>CS02</Code><Msg>银联支付无返回或者返回异常</Msg></Result>";
				}
				
			}else{           //支付
				RealOrderNo=Util.ReturnCode();
				return_xml=PayProcess(dataSource1,IVROrderNo,RealOrderNo,BankAccount);
			}	
		}else{        //支付
			String RealOrderNo=Util.ReturnCode();
			return_xml=PayProcess(dataSource1,OrderNo,RealOrderNo,BankAccount);
		}
		try{
			response.setCharacterEncoding("gb2312");
			response.setContentType("text/html;charset=UTF-8");
		    PrintWriter out=response.getWriter();;
			PorcessLog(return_xml,OrderNo,"返回IVR","pay_04",100,"",dataSource1);
			log.info("return_xml:"+return_xml);
			out=response.getWriter();
			out.print(return_xml);
		}catch(Exception e){
			log.error(Util.getERRO(e));
		}
	}
}
